package com.lebang.controller.buss;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lebang.common.ExeclUtil;
import com.lebang.common.Login;
import com.lebang.component.AsyncsComponent;
import com.lebang.component.RedisClient;
import com.lebang.entity.member.LbbMember;
import com.lebang.entity.member.LbbMemberRecord;
import com.lebang.entity.task.LbbSosoWithBLOBs;
import com.lebang.entity.task.TaskScreenshot;
import com.lebang.example.LbbMemberRecordExample;
import com.lebang.example.TaskClassifyExample;
import com.lebang.example.TaskTagExample;
import com.lebang.model.enums.Booleans;
import com.lebang.model.enums.Status;
import com.lebang.model.enums.buss.RewardMode;
import com.lebang.model.enums.buss.RewardType;
import com.lebang.model.enums.buss.TaskCategory;
import com.lebang.model.enums.buss.TaskStatus;
import com.lebang.model.vo.buss.TaskSearchVo;
import com.lebang.service.TaskClassifyService;
import com.lebang.service.TaskScreenshotService;
import com.lebang.service.TaskTagService;
import com.lebang.service.buss.AppStoreService;
import com.lebang.service.buss.CustomService;
import com.lebang.service.buss.MemberRecordService;
import com.lebang.service.buss.MemberService;
import com.lebang.service.task.TaskService;
import com.lebangweb.common.DateUtil;
import com.lebangweb.common.UUIDUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;

/**
 * Soso任务管理
 *
 * @author weizx
 * @date 2018年7月16日 上午10:16:03
 */
@Controller
public class SosoController {
    @Autowired
    private RedisClient redisClient;


    @Autowired
    private AppStoreService appStoreService;


    @Autowired
    private MemberRecordService memberRecordService;

    @Autowired
    private CustomService customService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private AsyncsComponent asyncs;

    @Autowired
    @Qualifier(value = "sosoTaskService")
    private TaskService<LbbSosoWithBLOBs> sosoService;

    @Autowired
    private TaskScreenshotService taskScreenshotService;
    @Autowired
    private TaskClassifyService taskClassifyService;
    @Autowired
    private TaskTagService taskTagService;

    @RequestMapping(value = "/soso/list", method = {RequestMethod.GET})
    @Login
    public String list(Model model, HttpServletRequest request, HttpSession session) {
        model.addAttribute("booleans", Booleans.values());
        model.addAttribute("rewards", RewardMode.values());
        model.addAttribute("types", RewardType.values());
        model.addAttribute("Status", Status.values());
        model.addAttribute("appStores", appStoreService.getAppStore());
        return "/soso/list";
    }

    @Login
    @RequestMapping(value = "/soso/list", method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> getList(TaskSearchVo vo, HttpServletRequest request, HttpSession session) {
        return sosoService.list(vo);
    }

    @Login
    @RequestMapping(value = "/soso/insert", method = {RequestMethod.GET})
    public String insert(Model model, HttpServletRequest request, HttpSession session) {
        model.addAttribute("booleans", Booleans.values());
        model.addAttribute("rewards", RewardMode.values());
        model.addAttribute("types", RewardType.values());
        model.addAttribute("appStores", appStoreService.getAppStore());
        model.addAttribute("customlist", customService.getAllCustomList());
        TaskClassifyExample taskClassifyExample = new TaskClassifyExample();
        taskClassifyExample.createCriteria().andEnableEqualTo(1).andHasDeletedEqualTo("False");
        TaskTagExample taskTagExample = new TaskTagExample();
        taskTagExample.createCriteria().andEnableEqualTo(1).andHasDeletedEqualTo("False");
        model.addAttribute("taskClassifys",taskClassifyService.selectByExample(taskClassifyExample));
        model.addAttribute("taskTags",taskTagService.selectByExample(taskTagExample));
        return "/soso/edit";
    }

    @Login
    @RequestMapping(value = "/soso/save", method = {RequestMethod.POST})
    @ResponseBody
    public String save(LbbSosoWithBLOBs task, TaskScreenshot taskScreenshot, HttpServletRequest request, HttpSession session) {
        taskScreenshot.setCategory(TaskCategory.Soso.name());
        taskScreenshot.setIsMultiword(0);
        if (null == task.getTaskId() || "".equals(task.getTaskId())) {
            task.setTaskId(UUIDUtil.L());
            taskScreenshot.setTaskId(task.getTaskId());
            asyncs.recordToMember(task.getTitle(), task.getTaskId());
            task.setTaskScreenshot(taskScreenshot);
            sosoService.insertTask(task);
        } else {
            LbbSosoWithBLOBs newtask = sosoService.taskInfoByTaskId(task.getTaskId());
            if (task.getShowinhp() == null) {
                task.setShowinhp((byte) 0);
            }
            task.setCreateTime(newtask.getCreateTime());
            LbbSosoWithBLOBs lo = sosoService.taskInfoByTaskId(task.getTaskId());
            task.setId(lo.getId());
            task.setTaskScreenshot(taskScreenshot);
            sosoService.updateTask(task);
        }
        return "保存成功！";
    }

    @Login
    @RequestMapping(value = "/soso/edit/{taskid}", method = {RequestMethod.GET})
    public String edit(@PathVariable(value = "taskid") String taskid, Model model, HttpServletRequest request,
                       HttpSession session) {
        model.addAttribute("customlist", customService.getAllCustomList());
        model.addAttribute("booleans", Booleans.values());
        model.addAttribute("rewards", RewardMode.values());
        model.addAttribute("types", RewardType.values());
        model.addAttribute("appStores", appStoreService.getAppStore());
        model.addAttribute("task", sosoService.taskInfoByTaskId(taskid));
        model.addAttribute("tags",taskScreenshotService.selectRelation(taskid));
        TaskScreenshot taskScreenshot = taskScreenshotService.selectByTaskId(taskid);
        model.addAttribute("taskScreenshot",taskScreenshot);
        TaskClassifyExample taskClassifyExample = new TaskClassifyExample();
        taskClassifyExample.createCriteria().andEnableEqualTo(1).andHasDeletedEqualTo("False");
        TaskTagExample taskTagExample = new TaskTagExample();
        taskTagExample.createCriteria().andEnableEqualTo(1).andHasDeletedEqualTo("False");
        model.addAttribute("taskClassifys",taskClassifyService.selectByExample(taskClassifyExample));
        model.addAttribute("taskTags",taskTagService.selectByExample(taskTagExample));
        return "/soso/edit";
    }

    /**
     * 删除
     *
     * @param taskid
     * @param request
     * @param session
     * @return
     * @author weizx
     * @date 2018年7月31日 下午6:30:11
     */
    @Login
    @RequestMapping(value = "/soso/del", method = {RequestMethod.POST})
    @ResponseBody
    public String del(@RequestParam(value = "taskid") String taskid, HttpServletRequest request, HttpSession session) {
        LbbSosoWithBLOBs task = sosoService.taskInfoByTaskId(taskid);
        if (task == null) {
            return "任务不存在！";
        }
        LbbSosoWithBLOBs lo = sosoService.taskInfoByTaskId(task.getTaskId());
        task.setId(lo.getId());
        sosoService.deleteTask(task);
        return "删除成功！";
    }

    /**
     * 上架
     *
     * @param request
     * @param session
     * @return
     */
    @Login
    @RequestMapping(value = "/soso/start", method = {RequestMethod.POST})
    @ResponseBody
    public String start(@RequestParam(value = "taskid") String taskid, HttpServletRequest request, HttpSession session) {
        LbbSosoWithBLOBs so = sosoService.taskInfoByTaskId(taskid);

        if (so.getStatus().equals(Status.Off)) {
            so.setStatus(Status.On);
        } else {
            so.setStatus(Status.Off);
        }

        sosoService.updateTask(so);
        return "修改成功！";
    }

    /**
     * 审核列表
     *
     * @param model
     * @param request
     * @param session
     * @return
     * @author weizx
     * @date 2018年8月1日 下午2:28:13
     */
    @Login
    @RequestMapping(value = "/soso/checkList", method = {RequestMethod.GET})
    public String checkList(Model model, HttpServletRequest request, HttpSession session) {
        String status = request.getParameter("status");
        if (status != null && !"".equals(status)) {
            model.addAttribute("_status", status);
        }
        String title = request.getParameter("_title");
        if (title != null && !"".equals(title)) {
            model.addAttribute("_title", title);
        }
        model.addAttribute("taskStatus", TaskStatus.values());
        return "/soso/checkList";

    }

    /**
     * 审核列表
     *
     * @param status
     * @param request
     * @param session
     * @return
     * @author weizx
     * @date 2018年8月1日 下午3:52:11
     */
    @Login
    @RequestMapping(value = "/soso/checkList", method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> getCheckList(String status, String stime, String etime, Integer offset, Integer limit,
                                            String customer, String title, HttpServletRequest request, HttpSession session, String phone) {
        String category = TaskCategory.Soso.name();
        return memberRecordService.pagging(category, status, stime, etime, offset, limit, title, customer, phone, 1);
    }

    /**
     * 审核页面
     *
     * @param taskid
     * @param model
     * @param request
     * @param session
     * @return
     * @author weizx
     * @date 2018年8月1日 下午5:11:23
     */
    @Login
    @RequestMapping(value = "/soso/check/{memberid}/{taskid}", method = {RequestMethod.GET})
    public String check(@PathVariable(value = "memberid") String memberid,
                        @PathVariable(value = "taskid") String taskid, Model model, HttpServletRequest request,
                        HttpSession session) {
        LbbMemberRecord record = memberRecordService.checkRecord(memberid, taskid, TaskCategory.Soso.name());

        if (record != null) {
            model.addAttribute("result", JSONArray.parseArray(record.getResult()));
            model.addAttribute("task", sosoService.taskInfoByTaskId(taskid));
            LbbMember member = memberService.getMemberByMemberId(record.getMemberId());
            if (member != null) {
                model.addAttribute("member", member);
            }
        }
        return "/soso/check";
    }

    @Login
    @RequestMapping(value = "/soso/check", method = {RequestMethod.POST})
    @ResponseBody
    public JsonData checks(@RequestParam(value = "memberid") String memberid,
                           @RequestParam(value = "taskid") String taskid, @RequestParam(value = "status") String status,
                           @RequestParam(value = "remark", required = false) String remark, HttpServletRequest request,
                           HttpSession session) {
        LbbMemberRecord record = memberRecordService.checkRecord(memberid, taskid, TaskCategory.Soso.name());
        if (record == null) {
            return Callback.fail("fail", "操作失败", null);
        }
        List<String> list = new ArrayList<>(1);
        list.add(record.getId().toString());
        int i = sosoService.examineAndVerify(list, "", status, remark,1);
        if (i > 0) {
            return Callback.success("success", "操作成功", null);
        } else {
            return Callback.fail("fail", "操作失败", null);
        }
    }


    @Login
    @RequestMapping(value = "/soso/detail", method = {RequestMethod.POST})
    @ResponseBody
    public Object detail(@RequestParam(value = "memberid") String memberid,
                         @RequestParam(value = "taskid") String taskid, HttpServletRequest request, HttpSession session) {
        LbbMemberRecord record = memberRecordService.checkRecord(memberid, taskid, TaskCategory.Soso.name());
        if (record == null) {
            return "记录不存在！";
        }
        return record;
    }

        @Login
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/soso/export", method = {RequestMethod.GET, RequestMethod.POST})
    public void export(@RequestParam(value = "taskid") String taskid,
                       @RequestParam(value = "upStatus") String upStatus, HttpServletRequest request,
                       HttpServletResponse response, HttpSession session) {
        try {
            LbbSosoWithBLOBs task = sosoService.taskInfoByTaskId(taskid);
            if (task == null) {
                return;
            }
            if (upStatus == null) {
                return;
            }
            if (upStatus.equals(TaskStatus.WaitCheckout.name()) || "WaitCheckout".equals(upStatus)) {
                List<LbbMemberRecord> records = getRecords(taskid, TaskStatus.WaitCheckout);
                List<Map<String, Object>> data = new ArrayList<>();
                Map<String, String> cols = new LinkedHashMap<>();
                for (LbbMemberRecord record : records) {
                    Map<String, Object> json = JSON.parseObject(JSONObject.toJSONString(record));
                    String result = record.getResult();
                    JSONArray array = JSONArray.parseArray(result);

                    for (int i = 0; i < array.size(); i++) {
                        JSONObject j = array.getJSONObject(i);
                        cols.put("pic" + i, "截图" + (i + 1));
                        String url = j.get("image") + "";
                        json.put("pic" + i, url);
                    }
                    LbbMember member = memberService.getMemberByMemberId(record.getMemberId());
                    if (member == null) {
                        continue;
                    }
                    json.put("createTime", DateUtil.dateToString(record.getCreateTime(), "yyyy-MM-dd HH:mm"));
                    json.put("phone", member.getPhone());
                    json.put("status", record.getStatus().getTitle());
                    data.add(json);
                }

                response.setCharacterEncoding("utf-8");
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(task.getTitle(), "utf-8") + ".xls ");
                Map<String, String> columns = new LinkedHashMap<>();
                columns.put("status", "审核结果");
                columns.put("createTime", "任务时间");
                columns.put("phone", "手机号");
                columns.put("imei", "设备标识");
                columns.putAll(cols);
                ExeclUtil.write(columns, data, response.getOutputStream());
            } else {
                List<LbbMemberRecord> records = getRecords(taskid, TaskStatus.CheckSuccess);
                List<LbbMemberRecord> record2 = getRecords(taskid, TaskStatus.CheckFailure);
                records.addAll(record2);
                List<Map<String, Object>> data = new ArrayList<>();
                Map<String, String> cols = new LinkedHashMap<>();
                for (LbbMemberRecord record : records) {
                    Map<String, Object> json = JSONObject.parseObject(JSON.toJSONString(record));
                    String result = record.getResult();
                    JSONArray array = JSONArray.parseArray(result);

                    for (int i = 0; i < array.size(); i++) {
                        JSONObject j = array.getJSONObject(i);
                        cols.put("pic" + i, "截图" + (i + 1));
                        String url = j.get("image") + "";
                        json.put("pic" + i, url);
                    }
                    LbbMember member = memberService.getMemberByMemberId(record.getMemberId());
                    if (member == null) {
                        continue;
                    }
                    json.put("createTime", DateUtil.dateToString(record.getCreateTime(), "yyyy-MM-dd HH:mm"));
                    json.put("phone", member.getPhone());
                    json.put("status", record.getStatus().getTitle());
                    data.add(json);
                }
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(task.getTitle(), "utf-8") + ".xls ");
                Map<String, String> columns = new LinkedHashMap<>();
                columns.put("status", "审核结果");
                columns.put("createTime", "任务时间");
                columns.put("phone", "手机号");
                columns.put("imei", "设备标识");
                columns.putAll(cols);
                ExeclUtil.write(columns, data, response.getOutputStream());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private List<LbbMemberRecord> getRecords(String taskid, TaskStatus status) {
        LbbMemberRecordExample lbbMemberRecordExample = new LbbMemberRecordExample();
        LbbMemberRecordExample.Criteria criteria = lbbMemberRecordExample.createCriteria();
        criteria.andTaskIdEqualTo(taskid);
        criteria.andCategoryEqualTo(TaskCategory.Soso.name());
        criteria.andNeedCheckedEqualTo("True");
        criteria.andStatusEqualTo(status.name());
        List<LbbMemberRecord> records = memberRecordService.getListByExample(lbbMemberRecordExample);
        return records;
    }

    @Login
    /**批量审核入口**/
    @PostMapping("/soso/checkselectlist")
    @ResponseBody
    public JsonData checklist(HttpServletRequest request, String data, String tab, @RequestParam(value = "status") String status, @RequestParam(value = "remark", required = false) String remark) {
        List<String> list = Arrays.asList(data.split(","));
        String uuid = UUIDUtil.M();
        boolean lock = redisClient.tryGetDistributedLock("lock:soso", uuid, 60000);
        if (!lock) {
            return Callback.fail("200", "操作过于频繁!", null);
        }
        int i = sosoService.examineAndVerify(list, tab, status, remark,1);
        redisClient.releaseDistributedLock("lock:soso", uuid);
        if (i != 1) {
            return Callback.fail("200", "批量审核失败", null);
        } else {
            return Callback.success("200", "批量审核成功", null);
        }

    }

    @PostMapping("/soso/starSosoTask")
    @ResponseBody
    public JsonData starMultiwordTask() {

        if (sosoService.starTaskAmount(LocalDateTime.now())) {
            return Callback.success("success", "操作成功", null);
        } else {
            return Callback.fail("fail", "操作失败", null);
        }
    }


    /**
     * 把旧表数据补全到新表内
     * @return
     */
    @Login
    @PostMapping("/soso/checkData")
    @ResponseBody
    public JsonData checkData(){

        String uuid = UUIDUtil.M();
        boolean lock = redisClient.tryGetDistributedLock("SOSOCHECK:KEY", uuid, 10000);
        if (!lock) {
            return Callback.fail("fail", "勿重复操作", null);
        }

        List<LbbSosoWithBLOBs> list = sosoService.taskList(null,null);
        try{
            list.forEach(s->{
                TaskScreenshot taskScreenshot = taskScreenshotService.selectByTaskId(s.getTaskId());
                if(taskScreenshot==null){
                    TaskScreenshot taskScreen = new TaskScreenshot(s);
                    taskScreenshotService.insert(taskScreen);

                }
            });
        }catch (Exception e){
            e.printStackTrace();
            return Callback.fail("fail", "操作失败", null);
        }finally {
            redisClient.releaseDistributedLock("SOSOCHECK:KEY", uuid);
        }

        return Callback.success("success", "操作成功", null);
    }

    @Login
    @RequestMapping(value = "/soso/copyData/{taskid}", method = {RequestMethod.GET})
    public String copyDataInsert(@PathVariable(value = "taskid") String taskid, Model model, HttpServletRequest request,
                       HttpSession session) {
        model.addAttribute("customlist", customService.getAllCustomList());
        model.addAttribute("booleans", Booleans.values());
        model.addAttribute("rewards", RewardMode.values());
        model.addAttribute("types", RewardType.values());
        model.addAttribute("appStores", appStoreService.getAppStore());
        LbbSosoWithBLOBs task = sosoService.taskInfoByTaskId(taskid);
        task.setId(null);
        task.setTaskId(null);
        model.addAttribute("task", task);
        model.addAttribute("tags",taskScreenshotService.selectRelation(taskid));
        TaskScreenshot taskScreenshot = taskScreenshotService.selectByTaskId(taskid);
        model.addAttribute("taskScreenshot",taskScreenshot);
        model.addAttribute("taskClassifys",taskClassifyService.selectByExample(null));
        model.addAttribute("taskTags",taskTagService.selectByExample(null));
        return "/soso/edit";
    }

}
